const app = getApp()

const log = require('../utils/log.js'); 

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/*
 * 验证手机号
 */
function testMobile(num) {
  var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(16[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
  if (num.length == 0) { 
      return false;
  }
  else
  {
    if (num.length < 11) { 
        return false;
    } else {
         if(!myreg.test(num))
         {
             return false;
        } 
    }
  } 
  return true;  
}
/*
* 显示错误信息
*/
function showErrorToast(msg,timeOut,title) {
  console.log(msg);
  if(!timeOut)
  {
    wx.showToast({
        title: msg,
        icon: 'none'
    })
  }
  else
  {
      if(timeOut===999999)
      {
          let t = '警告';
          if(title!=null && title!=''){
            t = title;
          }
          wx.showModal({
            title: t,
            content: msg, 
            showCancel: false,//是否显示取消按钮  
            confirmText:"确认",//默认是“确定”
            confirmColor: '#576B95',//确定文字的颜色，必须是 16 进制格式的颜色字符串
            success: function (res) {
              if (res.confirm) {
                  //点击确定执行的事件
                  wx.exitMiniProgram();
              }  
            },
            fail: function (res) { },//接口调用失败的回调函数
            complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
 
      }
      else
      {
          wx.showToast({
              title: msg,
              icon: 'none',
              duration: timeOut
          });
      }
  }

}
/*
* 显示成功信息
*/
function showSuccessToast(msg,timeOut) {
if(!timeOut)
{
  wx.showToast({
      title: msg,
      icon: 'success'
  })
}
else
{
  wx.showToast({
      title: msg,
      icon: 'success',
      duration: timeOut
  })
}
}

/**
 * 封封微信的的request
 */
function request2(url, data = {}, method = "GET") { 
  return new Promise(function(resolve, reject) {
      wx.request({
          url: url,
          data: data,
          method: method,
          header: {
              'Access-Control-Allow-Credentials': 'true',
              'Content-Type': 'application/json; charset=utf-8' 
          },
          success: function(res) {
            if (res.statusCode == 200) {
              resolve(res.data);
            }
            else if (res.statusCode == 401 || res.statusCode == 405)
            {
                reject('用户未登陆，请登录后操作');
            }
            else 
            {
                if(res.data.message)
                {
                    reject(res.data.message);
                }
                else
                {
                  log.error('接口调用错误1-->'+url+'-->'+JSON.stringify(data)+'-->'+JSON.stringify(res))
                  reject('接口调用错误');
                }
            }
          },
          fail: function(err) {
               log.error('接口调用错误2-->'+url+'-->'+JSON.stringify(data)+'-->'+JSON.stringify(err))
               reject('接口调用错误')
          }
      })
  });
}

function startLoading(infor) {
  wx.showLoading({
    title: infor,
    icon: 'none',
    mask: true
  });
  app.loadingClose = true;
}
function endLoading() {
  try{
     if(app.loadingClose)
     {
        wx.hideLoading();
     }
     app.loadingClose = false;
  }
  catch(err)
  {
    console.log(err);
  }
}

// 声明一个对象用于存储请求个数
 
function showFullScreenLoading(infor) {
  if (!app.needLoadingRequestCount || app.needLoadingRequestCount === 0) {
    startLoading(infor);
  }
  else
  {
    startLoading(infor);
  }
  app.needLoadingRequestCount++;
};
function tryHideFullScreenLoading(all) {
  if(all)
  {
    endLoading();
    return;
  }
  if (!app.needLoadingRequestCount || app.needLoadingRequestCount === 0) {
    endLoading();
    return;
  }
  app.needLoadingRequestCount--;
  if (app.needLoadingRequestCount === 0) {
    endLoading();
  }
}; 
function delay(milSec) {
 
  return new Promise(resolve => {
 
    setTimeout(resolve, milSec)
 
  })
 
}
function Second2String(MDSJ) {
  let h = parseInt(MDSJ / 3600);
  let m = parseInt((MDSJ % 3600) / 60);
  let s = (MDSJ - h * 3600 - m * 60) % 3600;
  let r = "";
  if (h > 0) {
      r = r + h.toString() + "小时";
  }
  //if (m > 0) {
  r = r + m.toString() + "分";
  //}
  //if (s > 0) {
  r = r + s.toString() + "秒";
  //}
  return r;
}

function base64_encode (str) { // 编码，配合encodeURIComponent使用
  var c1, c2, c3;
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var i = 0, len = str.length, strin = '';
  while (i < len) {
      c1 = str.charCodeAt(i++) & 0xff;
      if (i == len) {
          strin += base64EncodeChars.charAt(c1 >> 2);
          strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
          strin += "==";
          break;
      }
      c2 = str.charCodeAt(i++);
      if (i == len) {
          strin += base64EncodeChars.charAt(c1 >> 2);
          strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
          strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
          strin += "=";
          break;
      }
      c3 = str.charCodeAt(i++);
      strin += base64EncodeChars.charAt(c1 >> 2);
      strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
      strin += base64EncodeChars.charAt(c3 & 0x3F)
  }
  return strin
}

function base64_decode (input) { // 解码，配合decodeURIComponent使用
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var output = "";
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  while (i < input.length) {
      enc1 = base64EncodeChars.indexOf(input.charAt(i++));
      enc2 = base64EncodeChars.indexOf(input.charAt(i++));
      enc3 = base64EncodeChars.indexOf(input.charAt(i++));
      enc4 = base64EncodeChars.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
          output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
          output = output + String.fromCharCode(chr3);
      }
  }
  return utf8_decode(output);
}


function utf8_decode (utftext) { // utf-8解码
  var string = '';
  let i = 0;
  let c = 0;
  let c1 = 0;
  let c2 = 0;
  while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
          string += String.fromCharCode(c);
          i++;
      } else if ((c > 191) && (c < 224)) {
          c1 = utftext.charCodeAt(i + 1);
          string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
          i += 2;
      } else {
          c1 = utftext.charCodeAt(i + 1);
          c2 = utftext.charCodeAt(i + 2);
          string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
          i += 3;
      }
  }
  return string;
}
function sceneToObject(scene){
  //scene = decodeURIComponent(scene);
  let ret = {}
  let regParam = /([^&=]+)=([\w\W]*?)(&|$|#)/g
  let strParam = scene;
  let result
  while ((result = regParam.exec(strParam)) != null) {
    ret[result[1]] = result[2]
  }
  return ret;
}
module.exports = {
  formatTime,
  testMobile,
  showErrorToast,
  showSuccessToast,
  request2,
  startLoading,
  endLoading,
  showFullScreenLoading,
  tryHideFullScreenLoading,
  delay,
  Second2String,
  base64_encode,
  base64_decode,
  utf8_decode,
  sceneToObject
}
